import { DynamicIconEnum } from '@/platform/commons/enums/dynamic-icon-enum';
import React from 'react';
import './DynamicIcon.less';
import PropTypes from 'prop-types';
import DynamicIconType from '@/platform/types/dynamic-icon-type';
import * as AntIcon from '@ant-design/icons'
import Icon, { createFromIconfontCN } from '@ant-design/icons';

import { extendFonticonUrls, extendSvgIcons } from '@/shared/configs/extend-icon';

let IconFont:any;
if (extendFonticonUrls && extendFonticonUrls.length > 0) {
    IconFont = createFromIconfontCN({
        scriptUrl: extendFonticonUrls
    });
}

/**
 * 动态图标
 * @param props 参数
 * @returns 视图
 */
const DynamicIcon:React.FC<DynamicIconType> = (props) => {
    const getIcon = () => {
        if (props.iconName?.indexOf(DynamicIconEnum.SvgIcon) !== -1) {
            return (<Icon component={extendSvgIcons[props.iconName as string]} {...props.iconProps} />);
        }

        if (props.iconName?.indexOf(DynamicIconEnum.IconFont) !== -1) {
            const iconFont = props.iconName?.replace(DynamicIconEnum.IconFont, '');
            return (<IconFont type={iconFont as string} {...props.iconProps} />)
        }

        if (props.iconName?.indexOf(DynamicIconEnum.TagIcon) !== -1) {
            const tagIcon = props.iconName?.replace(DynamicIconEnum.TagIcon, '');
            const classList = ['iconfont', tagIcon].concat(props.tagIconCls ? props.tagIconCls : []);
            return (<span className={classList.join(' ')} {...props.iconProps} />);
        }

        return React.createElement(
            AntIcon[props.iconName as string],
            props.iconProps
        )
    }
    return (
        <>
            {
                getIcon()
            }
        </>
    )
};

DynamicIcon.propTypes = {
    iconName: PropTypes.string,
    iconProps: PropTypes.object,
    tagIconCls: PropTypes.array
}

DynamicIcon.defaultProps = {
    iconName: '',
    iconProps: {},
    tagIconCls: []
}

export default DynamicIcon;
